-------输出日志到文本-------
function print_file(data)
 
	local path = "ux0:/toolboxlog.txt"
	local output = io.open(path, "a")
	if output == nil then
		return 0
	end
	output:write(data.."\n")
	output:flush()
	output:close()

	return 1

end

-------锁home键------
function lock_home_key()

	if __HOME_KEY_IS_LOCKED then
		return
	end
	buttons.homepopup(0)
	__HOME_KEY_IS_LOCKED = true

end

-------解锁home键------
function unlock_home_key()

	if not __HOME_KEY_IS_LOCKED then
		return
	end
	buttons.homepopup(1)
	__HOME_KEY_IS_LOCKED = false

end

-------获取确定键------
function getButtonAssign()

	if buttons.assign() == 0 then
		BUTTON_POSITIVE = BUTTON_CIRCLE
		BUTTON_CANCEL = BUTTON_CROSS
		positive = "circle"
		cancel = "cross"
		button_assign = 0
	elseif buttons.assign() == 1 then
		BUTTON_POSITIVE = BUTTON_CROSS
		BUTTON_CANCEL = BUTTON_CIRCLE
		positive = "cross"
		cancel = "circle"
		button_assign = 1
	end
	
end

-------加载语言------
function loadLang()

	local defaultLangPath = "lang/chinese_s.txt"
	if checkFileExist(defaultLangPath) then
		dofile(defaultLangPath)
	end
	local langPath = "lang/"..os.language()..".txt"
	if checkFileExist(langPath) then
		dofile(langPath)
	end
	
end

-------加载字体------
function loadFont()

	if checkFileExist("resources/font/font.pgf") then
		fnt = font.load("resources/font/font.pgf")
	elseif checkFileExist("resources/font/font.ttf") then
		fnt = font.load("resources/font/font.ttf")
	elseif checkFileExist("resources/font/font.pvf") then
		fnt = font.load("resources/font/font.pvf")
	end
	if fnt then
		font.setdefault(fnt)
	end
	
end

-------加载背景图------
function loadBackground()

	--加载主背景图片
	if checkFileExist("resources/background/main_back.png") then
		BACKGROUND = image.load("resources/background/main_back.png")
	elseif checkFileExist("resources/background/main_back.jpg") then
		BACKGROUND = image.load("resources/background/main_back.jpg")
	end
	--重定义图片大小充满屏幕
	if BACKGROUND then
		if BACKGROUND:getw() ~= SCREEN_WIDTH or BACKGROUND:geth() ~= SCREEN_HEIGHT then
			image.resize(BACKGROUND, SCREEN_WIDTH, SCREEN_HEIGHT)
		end
	end
	--加载文本编辑器背景图片
	if checkFileExist("resources/background/texteditor_back.png") then
		TEXTEDITOR_BACKGROUND = image.load("resources/background/texteditor_back.png")
	elseif checkFileExist("resources/background/texteditor_back.jpg") then
		TEXTEDITOR_BACKGROUND = image.load("resources/background/texteditor_back.jpg")
	end
	if TEXTEDITOR_BACKGROUND then
		if TEXTEDITOR_BACKGROUND:getw() ~= SCREEN_WIDTH or TEXTEDITOR_BACKGROUND:geth() ~= SCREEN_HEIGHT then
			image.resize(TEXTEDITOR_BACKGROUND, SCREEN_WIDTH, SCREEN_HEIGHT)
		end
	else
		TEXTEDITOR_BACKGROUND = BACKGROUND
	end
	--加载文件管理器背景图片
	if checkFileExist("resources/background/explorer_back.png") then
		EXPLORER_BACKGROUND = image.load("resources/background/explorer_back.png")
	elseif checkFileExist("resources/background/explorer_back.jpg") then
		EXPLORER_BACKGROUND = image.load("resources/background/explorer_back.jpg")
	end
	if EXPLORER_BACKGROUND then
		if EXPLORER_BACKGROUND:getw() ~= SCREEN_WIDTH or EXPLORER_BACKGROUND:geth() ~= SCREEN_HEIGHT then
			image.resize(EXPLORER_BACKGROUND, SCREEN_WIDTH, SCREEN_HEIGHT)
		end
	else
		EXPLORER_BACKGROUND = BACKGROUND
	end

end

-------检测不安全模式------
function checkUnsafeMode()

	if os.access() == 1 then
		return
	end
	local state = MessageDialog(TIPS, SAFE_MODE_TIP, EXIT, JUMP_TO_SETTING)
	if state == 1 then
		os.uri("settings_dlg:")
	end
	os.exit()

end

-------删除临时升级用的app------
function deleteUpdateApp()

	if checkFolderExist("ux0:/app/ONEUPDATE") then
		game.delete("ONEUPDATE")
	end

end

-------保持后台运行------
function powerTickSuspend()

	if (wlan.isconnected() and ftp.state()) or (SOUND and sound.playing(SOUND)) then
		power.tick(__POWER_TICK_SUSPEND)
	end
 
end

------------播放背景音乐-------------------
function playBgmMusic()

	local bgmPath = "resources/bgm.mp3"
	if not checkFileExist(bgmPath) then
		return -1
	end
	SOUND = sound.load(bgmPath)
	if not SOUND then
		return -1
	end
	sound.play(SOUND)
	sound.loop(SOUND)
	music_playpos = nil
	music_playpath = bgmPath
	music_playname = "BGM"
	music_playmode = 2

end

------------自动播放下一首音乐------------
function autoPlayNextMusic()

	if music_playmode == nil or music_playmode == 2 or SOUND == nil or not sound.endstream(SOUND) then
		return -1
	end
	music_play_next()
 
end

----------------检测新版本-----------------------
function checkUpdater()
    
    HAVE_UPDATER = false
    UPDATER_VERSION = nil
    UPDATER_URL = nil
    CHECKING_UPDATER = true
    CHECK_UPDATER_FAILED = false
    UPDATER_THID = thread.new("git/thread_net.lua")
    
end

----------------获取后台进程新版本信息-----------------------
UPDATE_PORT = channel.new("UPDATE_PORT")

function getUpdateChannel()
    
    if not CHECKING_UPDATER then
        return
    end
    if UPDATE_PORT:available() <= 0 then
        return
    end
    CHECKING_UPDATER = false
    local info = UPDATE_PORT:pop()
    if not info[1] then
        CHECK_UPDATER_FAILED = true
        UPDATER_VERSION = nil
        UPDATER_URL = nil
        return
    end
    CHECK_UPDATER_FAILED = false
    UPDATER_VERSION = info[2]
    UPDATER_URL = info[3]
    if UPDATER_VERSION <= APP_VERSION then
        HAVE_UPDATER = false
        return
    end
    HAVE_UPDATER = true
    
end

----------------重定义刷新屏幕-----------------------
scr_flip = screen.flip
function screen.flip()
    
    getUpdateChannel()
	autoPlayNextMusic()
	powerTickSuspend()
	scr_flip()
 
end

----------------顶部状态栏构画-----------------------
function top_status_bar_draw(title)

	local padding_top = 12
	local padding_left = 18
	local status_bar_w = SCREEN_WIDTH
	local status_bar_h = padding_top + FONT_HEIGHT_DEFAULT + padding_top
	local status_bar_x = 0
	local status_bar_y = 0
	draw.fillrect(status_bar_x, status_bar_y, status_bar_w, status_bar_h, COLOR_STATUS_BAR_TRACK)
	
	local text_margin_left = 18
	local text_y = padding_top
	local textL_x = padding_left
	local textR_x = status_bar_x + status_bar_w - padding_left
	--标题
	screen.print(textL_x, text_y, title or "", FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK, __ALEFT, 460)
	--电量
	local batteryInt = batt.lifepercent()
	local batteryText = string.format(BATTERY_SHOW, batteryInt or "?")
	local batteryColor = COLOR_GREEN
	if batt.charging() then
		batteryColor = COLOR_YELLOW
	elseif batteryInt and batteryInt < 20 then
		batteryColor = COLOR_YELLOW
	end
	screen.print(textR_x, text_y, batteryText, FONT_SIZE_DEFAULT, batteryColor, COLOR_BLACK, __ARIGHT) 
	textR_x -= (screen.textwidth(batteryText) + text_margin_left)
	--时间
	local timeText = os.date("%Y/%m/%d   %H:%M")
	screen.print(textR_x, text_y, timeText, FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK, __ARIGHT)
	textR_x -= (screen.textwidth(timeText) + text_margin_left)
	--wifi & ftp
	local wifiText = "WiFi"
	local ftpText = "ftp"
	if wlan.isconnected() then
		screen.print(textR_x, text_y, wifiText, FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK, __ARIGHT)
		textR_x -= (screen.textwidth(wifiText) + text_margin_left)
		if ftp.state() then
			screen.print(textR_x, text_y, ftpText, FONT_SIZE_DEFAULT, COLOR_YELLOW, COLOR_BLACK, __ARIGHT)			
		end
	end
	
	return status_bar_h

end

----------------底部状态栏构画-----------------------
function bottom_status_bar_draw(textList)
	
	local padding_top = 12
	local padding_left = 18
	local status_bar_w = SCREEN_WIDTH
	local status_bar_h = padding_top + FONT_HEIGHT_DEFAULT + padding_top
	local status_bar_x = 0
	local status_bar_y = SCREEN_HEIGHT - status_bar_h
	draw.fillrect(status_bar_x, status_bar_y, status_bar_w, status_bar_h, COLOR_STATUS_BAR_TRACK)

	local text_margin_right = 20
	local text_x = padding_left
	local text_y = status_bar_y + padding_top
	--按键说明
	for i = 1, #textList do
		screen.print(text_x, text_y, textList[i] or "", FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
		text_x += (screen.textwidth(textList[i] or "") + text_margin_right)
	end
	
end

----------------ftp服务器-----------------------
function ftp_server()
 
	local wlanOn = false
	local ftpOn = false
	local oldWlanOn = false
	local oldFtpOn = false
	
	local title = FTP_SERVER
	local wlanMessage = ""
	local ftpMessage = ""
	local msg = ""

	local cancelButton = nil
	local positiveButton = nil
	local negativeButton = nil
	
	while true do
		if wlan.isconnected() then
			wlanOn = true
			wlanMessage = WLAN_ON
			if ftp.state() then
				ftpOn = true
				ftpMessage = string.format(FTP_ON_MESSAGE, tostring(wlan.getip()))
				cancelButton = KEEP_BACKGROUND
				positiveButton = CLOSE 
			else
				ftpOn = false
				ftpMessage = FTP_OFF_MESSAGE
				cancelButton = BACK
				positiveButton = START
			end
		else
			wlanOn = false
			wlanMessage = WLAN_OFF
			ftpMessage = ""
			cancelButton = BACK
			positiveButton = nil
		end
		oldWlanOn = wlanOn
		oldFtpOn = ftpOn
		msg = wlanMessage.."\n"..ftpMessage

		local msgList = {}

		--获取按键文字
		local buttonL_txt = cancelButton
		local buttonR_txt = positiveButton
		local buttonM_txt = negativeButton
		local buttonL_icon = BUTTON_CANCEL
		local buttonR_icon = BUTTON_POSITIVE
		local buttonM_icon = BUTTON_SQUARE
		if button_assign == 1 then
			buttonL_txt = positiveButton
			buttonR_txt = cancelButton
			buttonL_icon = BUTTON_POSITIVE
			buttonR_icon = BUTTON_CANCEL
		end
		if buttonR_txt then	--右键
			buttonR_txt = buttonR_icon..buttonR_txt
		end
		if buttonM_txt then	--中键
			buttonM_txt = buttonM_icon..buttonM_txt
		end
		if buttonL_txt then	--左键
			buttonL_txt = buttonL_icon..buttonL_txt
		end
		
		--获取构画信息--
		local padding_top = 16	--内上间距
		local padding_left = 30	--内左间距
		--标题
		local title_w = screen.textwidth(title or "", FONT_SIZE_DEFAULT)
		local title_h = FONT_HEIGHT_DEFAULT
		--信息
		local msg_margin_top = 20
		local msg_w = MESSAGE_DIALOG_WIDTH - padding_left*2
		breakStringByWidth(msgList, msg, msg_w)
		local msgListLen = #msgList
		local lineTotal = msgListLen
		if lineTotal < DIALOG_LINES_MIN then
			lineTotal = DIALOG_LINES_MIN
		elseif lineTotal > DIALOG_LINES_MAX then
			lineTotal = DIALOG_LINES_MAX
		end
		local msg_h = (FONT_HEIGHT_DEFAULT + MESSAGE_DIALOG_LINE_MARGIN)*lineTotal - MESSAGE_DIALOG_LINE_MARGIN
		--滚动条
		local scrollbar_track_margin_left = 6
		local scrollbar_track_w = 4
		local scrollbar_track_h = msg_h
		local scrollbar_w = scrollbar_track_w
		local scrollbar_h = scrollbar_track_h
		--按键
		local button_margin_top = msg_margin_top
		local button_margin_right = 20
		local button_h = FONT_HEIGHT_DEFAULT
		
		--弹窗总宽度
		DIALOG_WIDTH = padding_left + msg_w + padding_left
		
		--x轴--
		local dialog_x = string.format("%d", (SCREEN_WIDTH - DIALOG_WIDTH)/2)
		local title_x = (SCREEN_WIDTH - title_w)/2
		local msg_x = dialog_x + padding_left
		local scrollbar_track_x = msg_x + msg_w + scrollbar_track_margin_left
		local scrollbar_x = scrollbar_track_x
		
		local buttonL_w, buttonM_w, buttonR_w = 0, 0, 0
		local buttonL_x, buttonM_x, buttonR_x = 0, 0, 0
		local button_x_original = dialog_x + DIALOG_WIDTH - padding_left
		local button_x = button_x_original
		if buttonR_txt then	--右键
			buttonR_w = screen.textwidth(buttonR_txt, FONT_SIZE_DEFAULT)
			buttonR_x = button_x - buttonR_w
			button_x = buttonR_x - button_margin_right
		end
		if buttonM_txt then	--中键
			buttonM_w = screen.textwidth(buttonM_txt, FONT_SIZE_DEFAULT)
			buttonM_x = button_x - buttonM_w
			button_x = buttonM_x - button_margin_right
		end
		if buttonL_txt then	--左键
			buttonL_w = screen.textwidth(buttonL_txt, FONT_SIZE_DEFAULT)
			if button_x == button_x_original then
				button_x = button_x - 50
			end
			buttonL_x = button_x - buttonL_w
		end

		--弹窗总高度
		DIALOG_HEIGHT = padding_top + title_h + msg_margin_top + msg_h + button_margin_top + button_h + padding_top
		
		--y轴--
		local dialog_y = string.format("%d", (SCREEN_HEIGHT - DIALOG_HEIGHT)/2)	--弹窗y轴
		local title_y = dialog_y + padding_top
		local msg_y = title_y + title_h + msg_margin_top
		local scrollbar_track_y = msg_y
		local scrollbar_y = scrollbar_track_y
		local button_y = msg_y + msg_h + button_margin_top
			
		local top = 1
		local bottom = msgListLen
		local limit = msgListLen
		if limit > lineTotal then
			limit = lineTotal
		end
		local need_refresh = true
		
		DIALOG_TYPE = __MESSAGE_DIALOG_IS_SHOWING
		initDialog()
		
		while true do
			if wlan.isconnected() then
				wlanOn = true
				if ftp.state() then
					ftpOn = true
				else
					ftpOn = false
				end
			else
				wlanOn = false
			end
			
			if wlanOn ~= oldWlanOn or ftpOn ~= oldFtpOn then
				dismissDialog()
				break
			end
		
			MATH_FUNC[#MATH_FUNC].draw() --背景

			draw.fillrect(dialog_x, dialog_y, DIALOG_WIDTH, DIALOG_HEIGHT, COLOR_DIALOG_TRACK)	--弹窗区域
			draw.rect(dialog_x, dialog_y, DIALOG_WIDTH, DIALOG_HEIGHT, COLOR_DIALOG_STROKE)	--弹窗描边
		
			if need_refresh then
				scrollbar_h, scrollbar_y = refreshScrollbarStates(top, limit, msgListLen, scrollbar_track_h, scrollbar_track_y)
				top, bottom, _ = refreshListStates(top, nil, limit, msgListLen)
				need_refresh = false
			end

			--标题
			screen.print(title_x, title_y, title or "", FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
			--信息
			local list_y = msg_y
			if msgList and msgListLen > 0 then
				for i = top, bottom do
					screen.print(msg_x, list_y, msgList[i].text or "", FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
					list_y = list_y + MESSAGE_DIALOG_LINE_HEIGHT
				end

				if msgListLen > limit then --滚动条
					draw.fillrect(scrollbar_track_x, scrollbar_track_y, scrollbar_track_w, scrollbar_track_h, COLOR_SCROLL_BAR_TRACK) --滚动条背景
					draw.fillrect(scrollbar_x, scrollbar_y, scrollbar_w, scrollbar_h, COLOR_SCROLL_BAR) --滚动条
				end
			end
			--按键
			if buttonL_txt then	--左按键
				screen.print(buttonL_x, button_y, buttonL_txt, FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
			end
			if buttonM_txt then	--中按键
				screen.print(buttonM_x, button_y, buttonM_txt, FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
			end
			if buttonR_txt then	--右按键
				screen.print(buttonR_x, button_y, buttonR_txt, FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
			end

			screen.flip()

			buttons.read()
		
			if buttons.up or buttons.analogly < -60 then --↑键
				if top > 1 then
					top -= 1
					need_refresh = true
				end
			elseif buttons.down or buttons.analogly > 60 then --↓键
				if top < msgListLen - (limit - 1) then
					top += 1
					need_refresh = true
				end
			end

			if cancelButton and buttons[cancel] then --取消键
				buttons.read()
				dismissDialog()
				return 0
			elseif positiveButton and buttons[positive] then --确定键
				buttons.read()
				dismissDialog()
				if not ftp.state() then
					ftp.init()
					WaitDialog(WAIT_EXECUTING)
					os.delay(200)
				else
					local state = MessageDialog(TIPS, FTP_CLOSE_READY, CANCEL, POSITIVE)
					if state == 1 then
						ftp.term()
						WaitDialog(WAIT_EXECUTING)
						os.delay(200)
						dismissDialog()
					end
					return 1
				end
			elseif negativeButton and buttons.triangle then	--△键
				buttons.read()
				dismissDialog()
				return 2
			end
		end
	end
 
end

----------------usb连接-----------------------
function usb_connect()
 
	--0: USBDEVICE_MODE_MEMORY_CARD
	--1: USBDEVICE_MODE_GAME_CARD
	--2: USBDEVICE_MODE_SD2VITA
	--3: USBDEVICE_MODE_PSVSD

	--usb连接模式选择
	local usbModeEntries = {
		{text = USB_CONNECT_SELECT_MODE_MEMORY_CARD, enable = true},
		{text = USB_CONNECT_SELECT_MODE_SDTOVITA, enable = true},
	}
	if not USB_STARTED then
		usb_mode = -1
		local state = ItemDialog(USB_CONNECT_SELECT_CONNECT_CARD, usbModeEntries, CANCEL, POSITIVE)
		if state == 0 then
			return
		elseif state == 1 then
			usb_mode = 0 --MEMORY_CARD
		elseif state == 2 then
			usb_mode = 2 --SD2VITA
		end
		USB_CONNECT_SELECTED = usbModeEntries[state].text
	end
 
 lock_home_key() --锁home键
 
	--加载usb模块
	if not USB_REQUIRED then 
		WaitDialog(WAIT_EXECUTING)
		if os.requireusb() ~= 1 then
			unlock_home_key()
			MessageDialog(USB_CONNECT, USB_CONNECT_REQUIRE_USB_FAILED, BACK)
			return
		end
		USB_REQUIRED = true
	end
 
	--usb连接提示
	local usbOn = false
	local oldUsbOn = false
	
	local title = USB_CONNECT
	local msg = ""
	local cancelButton = nil
	local positiveButton = nil
	local negativeButton = nil
 
	while true do
		if usb.actived() == 1 then --如果usb设备已连接
			if not USB_STARTED then --启动u盘模式
				WaitDialog(WAIT_EXECUTING)
				if usb.start(usb_mode) == -1 then --如果启动失败
					usb.stop() --停止并退出
					unlock_home_key()
					MessageDialog(USB_CONNECT, USB_CONNECT_STARTED_FAILED, BACK)
					return
				end
				USB_STARTED = true
				os.delay(1000)
			end
			usbOn = true
			msg = USB_ON.."\n"..string.format(USB_CONNECT_MODE, USB_CONNECT_SELECTED)
		else
			usbOn = false
			msg = USB_OFF.."\n\n"..USB_CONNECT_NOT_CONNECTED
		end
		cancelButton = BACK
		positiveButton = nil
		if USB_STARTED then
			cancelButton = nil
			positiveButton = CLOSE
		end
		oldUsbOn = usbOn

		local msgList = {}

		--获取按键文字
		local buttonL_txt = cancelButton
		local buttonR_txt = positiveButton
		local buttonM_txt = negativeButton
		local buttonL_icon = BUTTON_CANCEL
		local buttonR_icon = BUTTON_POSITIVE
		local buttonM_icon = BUTTON_SQUARE
		if button_assign == 1 then
			buttonL_txt = positiveButton
			buttonR_txt = cancelButton
			buttonL_icon = BUTTON_POSITIVE
			buttonR_icon = BUTTON_CANCEL
		end
		if buttonR_txt then	--右键
			buttonR_txt = buttonR_icon..buttonR_txt
		end
		if buttonM_txt then	--中键
			buttonM_txt = buttonM_icon..buttonM_txt
		end
		if buttonL_txt then	--左键
			buttonL_txt = buttonL_icon..buttonL_txt
		end
		
		--获取构画信息--
		local padding_top = 16	--内上间距
		local padding_left = 30	--内左间距
		--标题
		local title_w = screen.textwidth(title or "", FONT_SIZE_DEFAULT)
		local title_h = FONT_HEIGHT_DEFAULT
		--信息
		local msg_margin_top = 20
		local msg_w = MESSAGE_DIALOG_WIDTH - padding_left*2
		breakStringByWidth(msgList, msg, msg_w)
		local msgListLen = #msgList
		local lineTotal = msgListLen
		if lineTotal < DIALOG_LINES_MIN then
			lineTotal = DIALOG_LINES_MIN
		elseif lineTotal > DIALOG_LINES_MAX then
			lineTotal = DIALOG_LINES_MAX
		end
		local msg_h = (FONT_HEIGHT_DEFAULT + MESSAGE_DIALOG_LINE_MARGIN)*lineTotal - MESSAGE_DIALOG_LINE_MARGIN
		--滚动条
		local scrollbar_track_margin_left = 6
		local scrollbar_track_w = 4
		local scrollbar_track_h = msg_h
		local scrollbar_w = scrollbar_track_w
		local scrollbar_h = scrollbar_track_h
		--按键
		local button_margin_top = msg_margin_top
		local button_margin_right = 20
		local button_h = FONT_HEIGHT_DEFAULT
		
		--弹窗总宽度
		DIALOG_WIDTH = padding_left + msg_w + padding_left
		
		--x轴--
		local dialog_x = string.format("%d", (SCREEN_WIDTH - DIALOG_WIDTH)/2)
		local title_x = (SCREEN_WIDTH - title_w)/2
		local msg_x = dialog_x + padding_left
		local scrollbar_track_x = msg_x + msg_w + scrollbar_track_margin_left
		local scrollbar_x = scrollbar_track_x
		
		local buttonL_w, buttonM_w, buttonR_w = 0, 0, 0
		local buttonL_x, buttonM_x, buttonR_x = 0, 0, 0
		local button_x_original = dialog_x + DIALOG_WIDTH - padding_left
		local button_x = button_x_original
		if buttonR_txt then	--右键
			buttonR_w = screen.textwidth(buttonR_txt, FONT_SIZE_DEFAULT)
			buttonR_x = button_x - buttonR_w
			button_x = buttonR_x - button_margin_right
		end
		if buttonM_txt then	--中键
			buttonM_w = screen.textwidth(buttonM_txt, FONT_SIZE_DEFAULT)
			buttonM_x = button_x - buttonM_w
			button_x = buttonM_x - button_margin_right
		end
		if buttonL_txt then	--左键
			buttonL_w = screen.textwidth(buttonL_txt, FONT_SIZE_DEFAULT)
			if button_x == button_x_original then
				button_x = button_x - 50
			end
			buttonL_x = button_x - buttonL_w
		end

		--弹窗总高度
		DIALOG_HEIGHT = padding_top + title_h + msg_margin_top + msg_h + button_margin_top + button_h + padding_top
		
		--y轴--
		local dialog_y = string.format("%d", (SCREEN_HEIGHT - DIALOG_HEIGHT)/2)	--弹窗y轴
		local title_y = dialog_y + padding_top
		local msg_y = title_y + title_h + msg_margin_top
		local scrollbar_track_y = msg_y
		local scrollbar_y = scrollbar_track_y
		local button_y = msg_y + msg_h + button_margin_top
			
		local top = 1
		local bottom = msgListLen
		local limit = msgListLen
		if limit > lineTotal then
			limit = lineTotal
		end
		local need_refresh = true
		
		DIALOG_TYPE = __MESSAGE_DIALOG_IS_SHOWING
		initDialog()
		
		while true do
			if usb.actived() == 1 then --如果usb设备已连接
				usbOn = true
			else
				usbOn = false
			end
			
			if usbOn ~= oldUsbOn then
				dismissDialog()
				break
			end
		
			MATH_FUNC[#MATH_FUNC].draw() --背景

			draw.fillrect(dialog_x, dialog_y, DIALOG_WIDTH, DIALOG_HEIGHT, COLOR_DIALOG_TRACK)	--弹窗区域
			draw.rect(dialog_x, dialog_y, DIALOG_WIDTH, DIALOG_HEIGHT, COLOR_DIALOG_STROKE)	--弹窗描边
		
			if need_refresh then
				scrollbar_h, scrollbar_y = refreshScrollbarStates(top, limit, msgListLen, scrollbar_track_h, scrollbar_track_y)
				top, bottom, _ = refreshListStates(top, nil, limit, msgListLen)
				need_refresh = false
			end

			--标题
			screen.print(title_x, title_y, title or "", FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
			--信息
			local list_y = msg_y
			if msgList and msgListLen > 0 then
				for i = top, bottom do
					screen.print(msg_x, list_y, msgList[i].text or "", FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
					list_y = list_y + MESSAGE_DIALOG_LINE_HEIGHT
				end

				if msgListLen > limit then --滚动条
					draw.fillrect(scrollbar_track_x, scrollbar_track_y, scrollbar_track_w, scrollbar_track_h, COLOR_SCROLL_BAR_TRACK) --滚动条背景
					draw.fillrect(scrollbar_x, scrollbar_y, scrollbar_w, scrollbar_h, COLOR_SCROLL_BAR) --滚动条
				end
			end
			--按键
			if buttonL_txt then	--左按键
				screen.print(buttonL_x, button_y, buttonL_txt, FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
			end
			if buttonM_txt then	--中按键
				screen.print(buttonM_x, button_y, buttonM_txt, FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
			end
			if buttonR_txt then	--右按键
				screen.print(buttonR_x, button_y, buttonR_txt, FONT_SIZE_DEFAULT, COLOR_TEXT_DEFAULT, COLOR_BLACK)
			end

			screen.flip()

			buttons.read()
		
			if buttons.up or buttons.analogly < -60 then --↑键
				if top > 1 then
					top -= 1
					need_refresh = true
				end
			elseif buttons.down or buttons.analogly > 60 then --↓键
				if top < msgListLen - (limit - 1) then
					top += 1
					need_refresh = true
				end
			end

			if cancelButton and buttons[cancel] then --取消键
				buttons.read()
				dismissDialog()
				unlock_home_key()
				return 0
			elseif positiveButton and buttons[positive] then --确定键
				buttons.read()
				dismissDialog()
				local state = MessageDialog(TIPS, USB_CONNECT_CLOSE_READY, CANCEL, POSITIVE)
				if state == 1 then --关闭usb连接
					WaitDialog(WAIT_EXECUTING)
					usb.stop()
					os.delay(200)
					USB_STARTED = false
					dismissDialog()
					unlock_home_key()
					return					
				end
				break
			elseif negativeButton and buttons.triangle then	--△键
				buttons.read()
				dismissDialog()
				unlock_home_key()
				return 2
			end
		end
	end
 
end

--------------安装游戏文件夹-------------------------------
function install_game_dir(path)
 
	local partitionPath = getRootPath(path)
	--如果安装包不在ux0盘符则返回错误
	if partitionPath ~= "ux0:" then
		return -20 --安装包不在ux0:
	end

	local originalPath = stripVirgule(path)
	local originalName = getFileName(originalPath)
	local install_mode = 1
	if checkFolderExist(originalPath.."/sce_pfs") then
		install_mode = 2
	end
	--检测安
	local ebootPath = originalPath.."/eboot.bin"
	local sfoPath = originalPath.."/sce_sys/param.sfo"
	if not checkFileExist(ebootPath) or not checkFileExist(sfoPath) then 
		return -11 --安装包不合法
	end
	--读取sfo
	local gameInfo = game.info(sfoPath)
	if not gameInfo or not gameInfo.TITLE_ID then  --如果sfo不合法
		return -12 --包装包有错误
	end
	local gameId = gameInfo.TITLE_ID --获取要安装的游戏ID
	if gameId == os.titleid() then
		return -13 --安装包为当前软件
	end
	--临时安装路径
	local tmpPath = "ux0:/temp/install"
	deletePath(tmpPath)
	createFolder(tmpPath)
	local tmpGamePath = tmpPath.."/"..originalName
	movePath(originalPath, tmpPath)
	files.rename(tmpGamePath, gameId)
	tmpGamePath = tmpPath.."/"..gameId
	--备份ux0:app/[GAMEID]
	local backPath = tmpPath.."/backup"
	local appGamePath = "ux0:/app/"..gameId
	local appGameBackupPath = backPath.."/"..gameId
	if checkFolderExist(appGamePath) then
		movePath(appGamePath, backPath)
	end
	--安装游戏
	local ret = -1    
	if install_mode == 1 then
		ret = game.installdir(tmpGamePath)
	else
		ret = game.refresh(tmpGamePath)
	end
	if ret == 1 then
		deletePath(appGameBackupPath)
	else
		--还原ux0:app/[GAMEID]的备份
		if checkFolderExist(appGameBackupPath) then
			movePath(appGameBackupPath, getParentPath(appGamePath))
		end
		--还原源安装包
		files.rename(tmpGamePath, originalName)
		tmpGamePath = tmpPath.."/"..originalName
		movePath(tmpGamePath, getParentPath(originalPath))
	end
	--删除临时目录
	deletePath(tmpPath)

	return ret
 
end

--------------安装游戏文件夹(自我安装)-------------------------------
function install_game_dir_self(path)
 	
	local do_home_key_lock = false
	if not __HOME_KEY_IS_LOCKED then
		lock_home_key()
		do_home_key_lock = true
	end
	
	
	
	if do_home_key_lock then
		unlock_home_key()
	end
	
	return ret
 
end

--------------重载变革配置文件-------------------------------
function taicfg_reload()

	local state = MessageDialog(TIPS, TAICFG_RELOAD_READY, CANCEL, POSITIVE)
	if state == 0 then
		return
	end
	
	WaitDialog(WAIT_EXECUTING)
	local state = os.taicfgreload()
	if state == 1 then
		MessageDialog(TIPS, TAICFG_RELOAD_COMPLETED, BACK)
	else
		MessageDialog(TIPS, TAICFG_RELOAD_FAILED, BACK)
	end
		
end

--------------重置变革配置文件-------------------------------
function taicfg_reset()

	local entries = {
		{text = TAICFG_RESET_UR, enable = true},
		{text = TAICFG_RESET_VS, enable = true},
	}

	local sel = ItemDialog(PLEASE_SELECT, entries, CANCEL, POSITIVE)
	if sel == 0 then
		return
	end
	local mode = sel
	
	local state = MessageDialog(TIPS, TAICFG_RESET_READY, CANCEL, POSITIVE)
	if state == 0 then
		return
	end
	
	WaitDialog(WAIT_EXECUTING)
	
	local partitionList = {"ux0:", "ur0:", "imc0:", "uma0:", "xmc0:"}
	local completed = false
	for i = 1, #partitionList do
		while true do
			local partitionPath = partitionList[i]
			local configPath = partitionPath.."/tai/config.txt"
			local configExist = checkFileExist(configPath)
			if not configExist then
				if partitionPath == "ur0:" then
					deletePath(configPath)
					if createFile(configPath) ~= 1 then
						break
					end
					configExist = true
				end
			else
				copyFile(configPath, configPath..".bak")
			end
			if not configExist then
				break
			end
			--写入文本
			local output = io.open(configPath, "w+")
			if output == nil then
				break
			end
			if partitionPath == "ur0:" then --ur0 config.txt
				output:write(TAI_CONFIG_STR0.."\n") --ur0 tip
			end   
			output:write(TAI_CONFIG_STR1.."\n") --body
			if mode == 1 then --henkaku in ur0
				output:write(TAI_CONFIG_STR2.."\n") --henkaku plugin str
			end
			output:close()
			completed = true
			break
		end
	end
	if completed then
		MessageDialog(TIPS, TAICFG_RESET_COMPLETED, BACK)
	else
		MessageDialog(TIPS, TAICFG_RESET_FAILED, BACK)
	end

end

---------------重构数据库--------------------------
function rebuilddb()
 
	deletePath("ur0:shell/db/app.db")

end

--------------解除记忆卡关连-------------------------------
function relink_mc()

	deletePath("ux0:id.dat")
	deletePath("imc0:id.dat")
	deletePath("uma0:id.dat")
	deletePath("xmc0:id.dat")

end

